package com.gt.service.impl;

import com.gt.context.BaseContext;
import com.gt.exception.PasswordEditFailedException;
import com.gt.mapper.EmployeeMapper;
import com.gt.pojo.dto.EmployeeDTO;
import com.gt.pojo.dto.UpdatePasswordDTO;
import com.gt.pojo.entity.Employee;
import com.gt.service.UserService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public Employee auth() {
        Long userId = BaseContext.getCurrentId();
        Employee employee = employeeMapper.getById(userId);
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        Long userId = BaseContext.getCurrentId();
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setId(userId);
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }

    @Override
    public void updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        Long currentId = BaseContext.getCurrentId();
        Employee employee = employeeMapper.getById(currentId);
        if (updatePasswordDTO.getNewPassword() == updatePasswordDTO.getConfirmPassword()){
            throw new PasswordEditFailedException("两次密码不一致");
        }
        if (updatePasswordDTO.getOldPassword().equals(employee.getPassword())){
            employee.setPassword(updatePasswordDTO.getConfirmPassword());
            employee.setId(currentId);
            employeeMapper.update(employee);
        }
    }
}
